import { NextResponse } from 'next/server';
import { SqliteDatabase } from '@/lib/sqlite-database';

export async function POST() {
  try {
    const db = new SqliteDatabase();
    
    // 开始事务
    db.db.prepare('BEGIN TRANSACTION').run();
    
    try {
      // 1. 重命名现有表为临时表
      db.db.prepare('ALTER TABLE naming_parameters RENAME TO temp_naming_parameters').run();
      db.db.prepare('ALTER TABLE position_parameters RENAME TO temp_position_parameters').run();
      db.db.prepare('ALTER TABLE base_parameters RENAME TO temp_base_parameters').run();
      
      // 2. 创建新表，使用id作为外键字段名
      db.db.prepare(`
        CREATE TABLE naming_parameters (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          id_device INTEGER NOT NULL,
          parameter_name TEXT NOT NULL,
          parameter_value TEXT,
          data_type TEXT,
          example_description TEXT,
          measurement_class TEXT,
          data_source TEXT,
          is_required BOOLEAN DEFAULT 0,
          created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
          updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
          FOREIGN KEY (id_device) REFERENCES devices (id) ON DELETE CASCADE
        )
      `).run();
      
      db.db.prepare(`
        CREATE TABLE position_parameters (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          id_device INTEGER NOT NULL,
          parameter_name TEXT NOT NULL,
          parameter_value TEXT,
          data_type TEXT,
          example_description TEXT,
          measurement_class TEXT,
          data_source TEXT,
          is_required BOOLEAN DEFAULT 0,
          created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
          updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
          FOREIGN KEY (id_device) REFERENCES devices (id) ON DELETE CASCADE
        )
      `).run();
      
      db.db.prepare(`
        CREATE TABLE base_parameters (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          id_device INTEGER NOT NULL,
          parameter_name TEXT NOT NULL,
          example_description TEXT,
          data_type TEXT,
          measurement_class TEXT,
          data_source TEXT,
          created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
          updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
          FOREIGN KEY (id_device) REFERENCES devices (id) ON DELETE CASCADE
        )
      `).run();
      
      // 3. 从临时表复制数据到新表
      db.db.prepare(`
        INSERT INTO naming_parameters (
          id_device, parameter_name, parameter_value, data_type, 
          example_description, measurement_class, data_source, is_required,
          created_at, updated_at
        )
        SELECT 
          device_id, parameter_name, parameter_value, data_type,
          example_description, measurement_class, data_source, is_required,
          created_at, updated_at
        FROM temp_naming_parameters
      `).run();
      
      db.db.prepare(`
        INSERT INTO position_parameters (
          id_device, parameter_name, parameter_value, data_type,
          example_description, measurement_class, data_source, is_required,
          created_at, updated_at
        )
        SELECT 
          device_id, parameter_name, parameter_value, data_type,
          example_description, measurement_class, data_source, is_required,
          created_at, updated_at
        FROM temp_position_parameters
      `).run();
      
      db.db.prepare(`
        INSERT INTO base_parameters (
          id_device, parameter_name, example_description, data_type,
          measurement_class, data_source, created_at, updated_at
        )
        SELECT 
          device_id, parameter_name, example_description, data_type,
          measurement_class, data_source, created_at, updated_at
        FROM temp_base_parameters
      `).run();
      
      // 4. 删除临时表
      db.db.prepare('DROP TABLE temp_naming_parameters').run();
      db.db.prepare('DROP TABLE temp_position_parameters').run();
      db.db.prepare('DROP TABLE temp_base_parameters').run();
      
      // 5. 创建索引
      db.db.prepare('CREATE INDEX idx_naming_parameters_id_device ON naming_parameters (id_device)').run();
      db.db.prepare('CREATE INDEX idx_position_parameters_id_device ON position_parameters (id_device)').run();
      db.db.prepare('CREATE INDEX idx_base_parameters_id_device ON base_parameters (id_device)').run();
      
      // 提交事务
      db.db.prepare('COMMIT').run();
      
      return NextResponse.json({
        success: true,
        message: '数据库表结构修复完成'
      });
      
    } catch (error) {
      // 如果出错，回滚事务
      db.db.prepare('ROLLBACK').run();
      throw error;
    }
    
  } catch (error) {
    console.error('修复数据库表结构时出错:', error);
    return NextResponse.json(
      { error: '修复数据库表结构失败: ' + error.message },
      { status: 500 }
    );
  }
} 